

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class ValueNotifierData extends ValueNotifier<String>{
  ValueNotifierData(super.value);
}

class _WidgetOne extends StatefulWidget {
  ValueNotifierData? data;
  _WidgetOne({this.data});


  @override
  State<StatefulWidget> createState() {
    return _WidgetOneState();
  }
}

class _WidgetOneState extends State<_WidgetOne>{

  String? info = null;

  @override
  void initState() {
    super.initState();
    widget.data?.addListener(_handleValueChange);
    info = 'Initial message: ${widget.data?.value}';
  }

  @override
  void dispose() {
    widget.data?.removeListener(_handleValueChange);
    super.dispose();
  }

  void _handleValueChange(){
    setState(() {
      info = 'Message changed to: ${widget.data?.value}' ;
    });
  }

  @override
  Widget build(BuildContext context) {
    print("_WidgetOneState build()");
    return Container(
      child: Center(
        child: Text(info??''),
      ),
    );
  }

}

class ParentValueNotifierCommunication extends StatelessWidget {


  @override
  Widget build(BuildContext context) {
    ValueNotifierData vd = ValueNotifierData('Hello World');
    return Scaffold(
      appBar: AppBar(title: Text('Value Notifier Communication'),),
      body: _WidgetOne(data: vd,),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.refresh),
        onPressed: (){
          vd.value = 'Yes';
        },
      ),
    );
  }

}